package com.venue.hjt.venueclass.service;

import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Environment;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

import com.google.gson.Gson;
import com.school.hjt.schoolclasscard.IMyAidlInterface;
import com.venue.hjt.venueclass.R;
import com.venue.hjt.venueclass.bean.API;
import com.venue.hjt.venueclass.bean.VenueBean;
import com.venue.hjt.venueclass.db.CardDao;
import com.venue.hjt.venueclass.db.VenueGroup;
import com.venue.hjt.venueclass.db.VenueSign;
import com.venue.hjt.venueclass.utlis.APPUtlis;
import com.venue.hjt.venueclass.utlis.AsyncTaskSoapUtil;
import com.venue.hjt.venueclass.utlis.ClassCalendar;
import com.venue.hjt.venueclass.utlis.Constant;
import com.venue.hjt.venueclass.utlis.OkhttPost;


import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import okhttp3.Call;

/**
 * Created by xqx on 2017/11/10.
 *
 */

public class RemoteService extends Service {
    private MyBinder binder;
    private ServiceConnection conn;
    Intent intent = new Intent();
    String  img;
    @Override
    public void onCreate() {
        super.onCreate();
        // System.out.println("远程进程开启");
        init();
        Timer timer = new Timer();

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                String etherNetIP = APPUtlis.getEtherNetIP();
                if (etherNetIP.equals("0.0.0.0")){
                    try {
                        APPUtlis.down();
                        APPUtlis.up();
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR, ClassCalendar.getStringtHour()+"  IP:"+etherNetIP);
                        sendBroadcast(intent);
                    } catch (IOException e) {
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"IP出错"+e.toString());
                        sendBroadcast(intent);
                        e.printStackTrace();
                    }
                }else{
                        intent.setAction(Constant.ERR);
                        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+"  IP:"+etherNetIP);
                        sendBroadcast(intent);
                }
                Heartbeat();
            }
        },10000,120000);

        timer.schedule(new TimerTask() {
            @Override
            public void run() {
                final List<VenueSign> venueSigns = CardDao.queryVenueSignType(0);
                for (int i=0;i<venueSigns.size();i++){
                    boolean sign_pattern = venueSigns.get(i).getSign_pattern();
                    if (sign_pattern){
                        final int finalI1 = i;
                        File file=new File(Environment.getExternalStorageDirectory().getPath()+"/Face/"+venueSigns.get(i).getId()+".te");
                        if (file.exists()){
                           Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
//                            Bitmap  bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.ss);
                            img = APPUtlis.bitmapToBase64(bitmap);
                            Log.e("ATG","进来img");
                        }
                        Log.e("ATG","进来");
                        Log.e("ATG",API.VENUESIGN + Constant.SNO + "&booking_id=" + venueSigns.get(i).getBooking_id()+"&signin_id=" + venueSigns.get(i).getMember_id() + "&card_no=" + venueSigns.get(i).getCard_no() + "&signin_time=" + ClassCalendar.getCardtime()+"&image="+img);
                       OkhttPost.Card(img, venueSigns.get(i).getBooking_id(), venueSigns.get(i).getMember_id(), venueSigns.get(i).getSignin_time(), new OkhttPost.Callback() {
                           @Override
                           public void onError(Call call, Exception e, int id) {

                           }
                           @Override
                           public void onResponse(String response, int id) {
                               Gson gson=new Gson();
                               VenueBean bean = gson.fromJson(response, VenueBean.class);
                               venueSigns.get(finalI1).setSign_type(1);
                               CardDao.updateVenueSignType(venueSigns.get(finalI1));
                               if (bean.code==1){
                                   List<VenueGroup> venueGroups = CardDao.queryGroupId(venueSigns.get(finalI1).getId());
                                   if (venueGroups.size()!=0){
                                       venueGroups.get(0).setSign("1");
                                       CardDao.updateVenueGroupType(venueGroups.get(0));
                                   }
                               }
                               intent.setAction(Constant.SIGN);
                               sendBroadcast(intent);
                           }
                       });
                    }else{
                        Log.e("ATG",API.VENUESIGN + Constant.SNO + "&booking_id=" + venueSigns.get(i).getBooking_id()+"&signin_id=" + venueSigns.get(i).getMember_id() + "&card_no=" + venueSigns.get(i).getCard_no() + "&signin_time=" + venueSigns.get(i).getSignin_time());
                        final int finalI = i;
                        OkhttPost.Okget(API.VENUESIGN + Constant.SNO + "&booking_id=" + venueSigns.get(i).getBooking_id()+"&signin_id=" + venueSigns.get(i).getMember_id() + "&card_no=" + venueSigns.get(i).getCard_no() + "&signin_time=" + venueSigns.get(i).getSignin_time(),
                                1, new OkhttPost.Callback() {
                                    @Override
                                    public void onError(Call call, Exception e, int id) {

                                    }
                                    @Override
                                    public void onResponse(String response, int id) {
                                        Log.e("ATG",response);
                                        Gson gson=new Gson();
                                        VenueBean bean = gson.fromJson(response, VenueBean.class);
                                        venueSigns.get(finalI).setSign_type(1);
                                        CardDao.updateVenueSignType(venueSigns.get(finalI));
                                        if (bean.code==1){
                                            List<VenueGroup> venueGroups = CardDao.queryGroupId(venueSigns.get(finalI).getId());
                                            if (venueGroups.size()!=0){
//                                                Log.e("ATG",venueGroups.size()+" 数量");
                                                venueGroups.get(0).setSign("1");
                                                CardDao.updateVenueGroupType(venueGroups.get(0));
                                            }
                                        }
                                    }
                                });
                    }
                }
            }
        },10000,10000);
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Intent intents = new Intent();
        intents.setClass(this, LocalService.class);
        bindService(intents, conn, Context.BIND_IMPORTANT);
        return START_STICKY;
    }
    private void init() {
        if (conn == null) {
            conn = new MyConnection();
        }
        binder = new MyBinder();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    static class MyBinder extends IMyAidlInterface.Stub {
        @Override
        public String getName() throws RemoteException {
            return "远程连接";
        }
    }

    //打卡考勤
    public void Timecard(String str2,AsyncTaskSoapUtil.Callback callback){
        String time= ClassCalendar.getCardtime();

        String namespace = "http://www.gcihjt.com/";//namespace
        String methodName = "UploadSwingCards";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        Log.e("debug",time);
        String md5="hjt"+time+"256B07301378445C83CB1A4D021FF4C7";
//        String md51 = AppUtlis.md5(md5);
        String md5Value = APPUtlis.getMd5Value(md5);
        Log.e("debug12",md5Value);
        map.put("Xml",str2);
        map.put("username","hjt");
        map.put("timeStr",time);
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(callback);
        soapUtil.execute();
    }
//    public void upSign(StudentSign cardStudent,int type){
//        StudentSign sign = new StudentSign(cardStudent.getId(), ClassCalendar.getStringMinuts(),type,ClassCalendar.getCardtime(),cardStudent.getCardnum(),"");
//        CardDao.updateSign(sign);
//        BaseApplication.getDaoInstant().clear();
//        intent.setAction(Constant.ERR);
//        intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 打卡数据上传给后台成功");
//        Log.e("ATG","打卡数据上传给后台成功");
//        sendBroadcast(intent);
//    }
    class MyConnection implements ServiceConnection {

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            System.out.println("获取远程连接");
        }

        @Override
        public void onServiceDisconnected(ComponentName nme) {
            RemoteService.this.startService(new Intent(RemoteService.this,
                    LocalService.class));
            RemoteService.this.bindService(new Intent(RemoteService.this,
                    LocalService.class), conn, Context.BIND_IMPORTANT);
        }
    }
    public void Heartbeat(){
        String time= ClassCalendar.getCardtime();
        String namespace = "http://www.gcihjt.com/";//namespace http://www.gcihjt.com/
        String methodName = "Heartbeat";//要调用的方法名称
        String WSDL_URI = "http://card.gcihjt.com/webcard.asmx";//wsdl 的uri
        Map<String,String> map=new HashMap<>();
        map.put("machineNo",android.os.Build.SERIAL);
        map.put("username","hjt");
        map.put("timeStr",time);
        String md5Value = APPUtlis.getMd5Value("hjt"+time+"256B07301378445C83CB1A4D021FF4C7");
        map.put("hashCode",md5Value);
        AsyncTaskSoapUtil soapUtil=new AsyncTaskSoapUtil(namespace,WSDL_URI,methodName,map);
        soapUtil.setCallback(new AsyncTaskSoapUtil.Callback() {
            @Override
            public void onPost(String data) {
                if (data.equals("00")){
                    Log.e("ATG","心跳包成功");
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 心跳包成功");
                    sendBroadcast(intent);
                }else {
                    intent.setAction(Constant.ERR);
                    intent.putExtra(Constant.ERR,ClassCalendar.getStringtHour()+": 心跳包失败 "+data);
                    sendBroadcast(intent);
                    Log.e("ATG"," 心跳包出错"+data);
                }
            }
        });
        soapUtil.execute();
    }
}